﻿namespace SharpTrainer
{
    public class Utility
    {
        public delegate bool ComparisonHandler(int first, int second);

        //Swap Two Variables
        public static void Swap(ref string first, ref string second)
        {
            string temp = first;
            first = second;
            second = temp;
        }

        /* Delegate Test Methods Start */

        public static bool GreaterThan(int first, int second)
        {
            return first > second;
        }

        public static bool LessThan(int first, int second)
        {
            return first < second;
        }

        public static bool AlphabeticalGreaterThan(int first, int second)
        {
            int comparison;

            comparison = (first.ToString().CompareTo(second.ToString()));

            return comparison > 0;
        }

        public static bool AlphabeticalLessThan(int first, int second)
        {
            int comparison;

            comparison = (first.ToString().CompareTo(second.ToString()));

            return comparison < 0;
        }

        /* Delegate Test Methods End */

        //Delegate Bubble Sort
        public static void BubbleSort(int[] items, ComparisonHandler comparisonMethod)
        {
            int i;
            int j;
            int temp;

            for (i = items.Length - 1; i >= 0; i--)
            {
                for (j = 1; j <= i; j++)
                {
                    if (comparisonMethod(items[j - 1], items[j]))
                    {
                        temp = items[j - 1];
                        items[j - 1] = items[j];
                        items[j] = temp;
                    }
                }
            }
        }

        //MD5 Algorithm
        public static string GetMD5(string dataStr, string codeType)
        {
            System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] t = md5.ComputeHash(System.Text.Encoding.GetEncoding(codeType).GetBytes(dataStr));
            System.Text.StringBuilder sb = new System.Text.StringBuilder(32);
            for (int i = 0; i < t.Length; i++)
            {
                sb.Append(t[i].ToString("x").PadLeft(2, '0'));
            }
            return sb.ToString();
        } 

        public static string GetSign(string dataStr, string key)
        {
            string sign = GetMD5(dataStr + key, "GB2312");
            return sign;
        }
    }
}
